package sk.ygor.xtemplate;

import java.util.regex.Pattern;
import java.util.regex.Matcher;

/**
 * User: ygor
 * Date: 13.11.2005
 * Time: 16:07:24
 */
public class ContentTokenizer {

    private static Pattern contentPattern =
            Pattern.compile("\\{\\$([A-Za-z0-9_]+)(?:\\.([A-Za-z0-9_]+))?\\}");

    private Matcher matcher;
    private int position;
    private ContentToken buffer;
    private String source;

    public ContentTokenizer(String source) {
        this.source = source;
        position = 0;
        matcher = contentPattern.matcher(source);
        buffer = null;
    }

    public ContentToken nextToken() {
        ContentToken result;
        if (buffer != null) {
            result = buffer;
            buffer = null;
            return result;
        }
        if (position == source.length()) {
            return null;
        }
        if (matcher.find()) {
            buffer = new ContentToken(ContentToken.VARIABLE, matcher.group(1), matcher.group(2));
            result = new ContentToken(ContentToken.TEXT, source.substring(position, matcher.start()), null);
            position = matcher.end();
        } else {
            result = new ContentToken(ContentToken.TEXT, source.substring(position, source.length()), null);
            position = source.length();
        }
        return result;
    }
}
